package com.banshuibao.bsb_android.download;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.FragmentActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.banshuibao.bsb_android.R;
import com.banshuibao.bsb_android.adapter.DownloadedAudioAdapter;
import com.banshuibao.bsb_android.adapter.VideoListViewAdapter;
import com.banshuibao.bsb_android.fragment.BaseFragment;
import com.banshuibao.bsb_android.model.DownloadAudioModel;
import com.banshuibao.bsb_android.model.DownloadInfo;
import com.banshuibao.bsb_android.model.DownloadedAudioModel;
import com.banshuibao.bsb_android.util.CCMediaConfig;
import com.banshuibao.bsb_android.util.DataSet;
import com.banshuibao.bsb_android.util.IntentManager;
import com.banshuibao.bsb_android.util.MediaUtil;
import com.bokecc.sdk.mobile.download.Downloader;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * 已下载标签页
 *
 * @author CC视频
 */
public class DownloadedAudioFragment extends BaseFragment implements DownloadedAudioAdapter.OnViewOnClickListener {

    private ListView downloadedListView;

    private List<DownloadedAudioModel> pairs;

    private TextView menu;

    private DownloadedAudioAdapter audioAdapter;

    private FragmentActivity activity;

    private DownloadedReceiver receiver;

    private boolean isCheckModel;

    private HashMap<String, String> deletes;

    private LinearLayout bottomLayout;

    private TextView all, delete;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        activity = getActivity();
        receiver = new DownloadedReceiver();
        activity.registerReceiver(receiver, new IntentFilter(CCMediaConfig.ACTION_AUDIO_DOWNLOADED));
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return LayoutInflater.from(activity).inflate(R.layout.fragment_downloaded, container, false);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        downloadedListView = view.findViewById(R.id.listView);
        downloadedListView.setDivider(null);
        bottomLayout = view.findViewById(R.id.bottom_layout);
        all = view.findViewById(R.id.all);
        delete = view.findViewById(R.id.delete);
        menu = activity.findViewById(R.id.menu);
        menu.setOnClickListener(l);
        all.setOnClickListener(l);
        delete.setOnClickListener(l);
        deletes = new HashMap<>();
        initData();
    }

    private View.OnClickListener l = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.all:
                    int listSize = audioAdapter.getList().size();
                    if (listSize == 0)
                        return;
                    int deleteSize = deletes.size();
                    if (deleteSize >= listSize) {
                        for (int i = 0; i < listSize; ++i) {
                            audioAdapter.getList().get(i).setCheck(false);
                        }
                        deletes.clear();
                    } else {
                        for (int i = 0; i < listSize; ++i) {
                            DownloadedAudioModel downloadInfo = audioAdapter.getList().get(i);
                            downloadInfo.setCheck(true);
                            for (DownloadedAudioModel.Data data : downloadInfo.getList()) {
                                deletes.put(data.getUuid(), null);
                            }
                        }
                    }
                    updateDeletesText();
                    audioAdapter.notifyDataSetChanged();
                    break;
                case R.id.delete:
                    if (deletes.size() == 0) {
                        return;
                    }
                    for (HashMap.Entry<String, String> entry : deletes.entrySet()) {
                        delete(entry.getKey());
                    }
                    deletes.clear();
                    updateDeletesText();
                    audioAdapter.notifyDataSetChanged();
                    break;
                case R.id.menu:
                    if (audioAdapter != null)
                        audioAdapter.stopMedia();
                    setCheckModel();
                    break;
            }
        }
    };

    private void updateDeletesText() {
        delete.setText(String.valueOf("删除" + "(" + deletes.size() + ")"));
    }

    private void initData() {
        pairs = new ArrayList<>();
        audioAdapter = new DownloadedAudioAdapter(activity);
        downloadedListView.setAdapter(audioAdapter);
        audioAdapter.OnViewOnClickListener(this);
        updateData();
    }

    private void updateData() {
        if (pairs != null)
            pairs.clear();
        else
            return;
        List<DownloadAudioModel> downloadInfos = DataSet.getDownloadAudioInfos();
        int size = downloadInfos.size();
        for (int i = 0; i < size; ++i) {
            DownloadAudioModel downloadInfo = downloadInfos.get(i);
            if (downloadInfo == null)
                continue;
            if (downloadInfo.getStatus() != Downloader.FINISH) {
                continue;
            }
            String groupId = downloadInfo.getGroupId();
            DownloadedAudioModel downloadedAudioModel = new DownloadedAudioModel();
            downloadedAudioModel.setImg(downloadInfo.getImg());
            downloadedAudioModel.setName(downloadInfo.getName());
            downloadedAudioModel.setGroupId(downloadInfo.getGroupId());
            downloadedAudioModel.setDuty(downloadInfo.getDuty());
            downloadedAudioModel.setQuestion(downloadInfo.getQuestion());
            List<DownloadedAudioModel.Data> list = new ArrayList<>();
            for (int j = 0; j < size; ++j) {
                DownloadAudioModel downloadInfo1 = downloadInfos.get(j);
                if (downloadInfo1 == null)
                    continue;
                if (downloadInfo1.getGroupId().equals(groupId)) {
                    DownloadedAudioModel.Data data = new DownloadedAudioModel.Data();
                    data.setContent(downloadInfo1.getContent());
                    data.setCreateTime(downloadInfo1.getCreateTime());
                    data.setVoiceTime(downloadInfo1.getVoiceTime());
                    data.setUrl(downloadInfo1.getUrl());
                    data.setUuid(downloadInfo1.getUuid());
                    data.setProgressText(downloadInfo1.getProgressText());
                    list.add(data);
                    downloadInfos.set(j, null);
                }
            }
            downloadedAudioModel.setList(list);
            pairs.add(downloadedAudioModel);
        }
        if (audioAdapter != null)
            audioAdapter.setPairs(pairs);
    }

    public void setCheckModel() {
        if (isHidden())
            return;
        isCheckModel = !isCheckModel;
        if (isCheckModel) {
            bottomLayout.setVisibility(View.VISIBLE);
            menu.setText("取消");
        } else {
            menu.setText("管理");
            setClearDelete();
        }
        audioAdapter.setShowCheck(isCheckModel);
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!isHidden()) {
            menu = activity.findViewById(R.id.menu);
            menu.setOnClickListener(l);
        }
        if (hidden) {
            setClearDelete();
        }
        if (audioAdapter != null)
            audioAdapter.stopMedia();
    }

    private void setClearDelete() {
        bottomLayout.setVisibility(View.GONE);
        menu.setText("管理");
        isCheckModel = false;
        int size = audioAdapter.getList().size();
        for (int i = 0; i < size; ++i) {
            audioAdapter.getList().get(i).setCheck(false);
        }
        deletes.clear();
        updateDeletesText();
        audioAdapter.setShowCheck(isCheckModel);
    }

    private void delete(String uuid) {
        DataSet.removeDownloadAudioInfo(uuid);
        File file = MediaUtil.getAudioFile(CCMediaConfig.DOWNLOAD_DIR, uuid);
        if (file.exists()) {
            file.delete();
        }
        updateData();
        DataSet.saveData();
    }

    @Override
    public void onClick(DownloadedAudioModel data1) {
        if (audioAdapter == null)
            return;
        if (isCheckModel) {
            data1.setCheck(!data1.isCheck());
            if (data1.isCheck()) {
                for (DownloadedAudioModel.Data data : data1.getList()) {
                    deletes.put(data.getUuid(), null);
                }
            } else {
                for (DownloadedAudioModel.Data data : data1.getList()) {
                    deletes.remove(data.getUuid());
                }
            }
            updateDeletesText();
            audioAdapter.notifyDataSetChanged();
        }
    }

    private class DownloadedReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            updateData();
        }

    }

    @Override
    public void onDestroy() {
        activity.unregisterReceiver(receiver);
        if (audioAdapter != null) {
            audioAdapter.clear();
            audioAdapter = null;
        }
        if (deletes != null) {
            deletes.clear();
            deletes = null;
        }
        super.onDestroy();
    }

}
